#include<allegro.h>
#include <stdio.h>
#include"leo.h"


/*int get_pixel(BITMAP* Buffer,int x,int y)
{
    int tmp;
    tmp=getpixel(Buffer,x,y);
    return((getr(tmp) + getb(tmp) + getg(tmp)) / 3);
}*/

void load_leo(Leo *leo)
{
    int i;
    char buf[50];

    for (i = 0; i < NB_IMAGES; i++)
    {

        sprintf(buf, "leo_right/right%d.bmp", i);
        leo->img_right[i] = load_bitmap(buf, NULL);
        sprintf(buf, "leo_left/left%d.bmp", i);
        leo->img_left[i] = load_bitmap(buf, NULL);
    }
}

void destroy_leo(Leo *leo)
{
    int i;
    for (i = 0; i < NB_IMAGES; i++)
    {
        destroy_bitmap(leo->img_right[i]);
        destroy_bitmap(leo->img_left[i]);
    }
}

void init_leo(Leo *leo)
{
    leo->direction = 0;
    leo->x = 80;
    leo->y = SCREEN_H-200;
}

void move_leo_right(Leo *leo,int *compteur)
{

    if (key[KEY_RIGHT] && (leo->x < SCREEN_W - leo->img_right[0]->w))
    {

        *compteur+=1;

        (leo->x)+=1;
        leo->direction = 0;
    }

}

void move_leo_left(Leo *leo,int *compteur)
{

    if (key[KEY_LEFT] && leo->x > 0)
    {

        *compteur+=1;

        (leo->x)-=1;
        leo->direction = 1;
    }
}

void jump_leo(Leo *leo)
{

    if (key[KEY_UP] && (leo->y > SCREEN_H/2))
    {
        (leo->y)-=150;
        (leo->x)++;
        leo->direction = 2;
    }
    if (leo->y < SCREEN_H-200)
        (leo->y)+=5;
}



void move_leo(Leo *leo,int *compteur)
{
    move_leo_right(leo,compteur);
    move_leo_left(leo,compteur);
    jump_leo(leo);
}

void draw_leo(Leo leo,BITMAP *Buffer, int compteur)
{
    static int last_direction;

    if (leo.direction == 0)
    {

        draw_sprite(Buffer, leo.img_right[compteur % (NB_IMAGES-1)],leo.x, leo.y);
        last_direction=0;
    }

    if(leo.direction == 1)
    {

        draw_sprite(Buffer, leo.img_left[compteur % (NB_IMAGES-1) ],leo.x, leo.y);
        last_direction=1;
    }
    if (leo.direction == 2 && last_direction==0)
    {
        draw_sprite(Buffer, leo.img_right[1],leo.x, leo.y);
        compteur=0;
    }
    if (leo.direction == 2 && last_direction==1)
    {
        draw_sprite(Buffer, leo.img_left[1],leo.x, leo.y);
        compteur=0;
    }
}
